import poplib,email,re,base64,time,os,sys
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
from urllib import request, parse
from http import cookiejar
sys.path.append(r"C:\language\python\jueceshu\venv\Lib\site-packages")
import bs4
import must_send

def check_mail():
    username="xox9002@126.com"
    pwd = "huang8121801"
    pop3_server = "pop.126.com"
    server = poplib.POP3(pop3_server)
    server.user(username)
    server.pass_(pwd)
    resp, mails, octets = server.list()
    index = len(mails)
    resp, lines, octets = server.retr(index)
    msg_content = b'\r\n'.join(lines).decode('utf-8')
    msg = Parser().parsestr(msg_content)
    email_subject=email.header.decode_header(msg['Subject'])
    title  = email_subject[0][0].decode(email_subject[0][1])
    if title.find("[DAKA]") != -1:
        return title;

    return  False;


#must_send.send_code_email("第一次打卡邮件，初始化");

i=0
z=0
k=0
while(1):

    title = None
    current_hours = int(time.strftime('%H',time.localtime()))

    if (current_hours >= 9 and current_hours < 10) or (current_hours >= 19 and current_hours <= 23):
        print("检查:{0}".format(current_hours))

        if k == 0 :
            must_send.send_code_email("程序运行第一次打卡邮件，初始化");
            k+=1
        elif k >= 1:
            title = check_mail()
            i += 1
    else:
        print("等待:{0}".format(current_hours))
        time.sleep(300)


    print("第[{0:d}]次检查邮件\n".format(i))

    if title is not False:
        receive = re.search(r'\](.*)$',str(title))

        if receive is not None:
            current_date = time.strftime(r"%Y%m%d")
            title_search = receive.group()
            daka_date = title_search[1:9]
            code = title_search[9:]

            if daka_date == current_date and len(code) > 0:
                user = "13767764441"
                pwd = "123456"
                url = r'http://oa.koudaikj.com/index.php?m=&c=clock&a=sign'
                headers = {
                    'User-Agent': r'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4549.400 QQBrowser/9.7.12900.400 ',
                    'Referer': r'http://oa.koudaikj.com/index.php?m=&c=clock&a=sign',
                    'Connection': 'keep-alive'
                }
                data = {
                    'mobile_tel': user,
                    'password': pwd,
                    'verify': code
                }
                data = parse.urlencode(data).encode('utf-8')
                cookie = cookiejar.MozillaCookieJar()
                cookie.load("code_c", ignore_discard=True, ignore_expires=True)
                cookie_support = request.HTTPCookieProcessor(cookie)
                opener = request.build_opener(cookie_support)
                req = request.Request(url, headers=headers, data=data)
                response = opener.open(req)

                if(response.code == 200):
                    z+=1
                    page = response.read()
                    page = page.decode('utf-8')
                    soup = bs4.BeautifulSoup(page,"html.parser")
                    result = soup.body.find(r'p')
                    meg = str(result)

                    if meg.find("success") is not None and meg.find("success") != -1:
                        f = open('success', 'w+')
                        f.write(meg)
                        f.close()
                        today_date = time.strftime("%Y%m%d")
                        must_send.send_code_email(content_text=meg,title="{0}打卡成功".format(today_date))
                        #打卡成功自动休眠4小时
                        k=0
                        time.sleep(60*60*4) 
                    else:
                        content_text = "第[{0:d}]次打卡失败\n".format(z)
                        content_text += "日期:[" + daka_date + "]" + "Code:" + code + "\n"
                        content_text += meg
                        must_send.send_code_email(content_text=content_text,title="POST打卡失败")
                        must_send.send_code_email(content_text="打卡失败，补发邮件。sleep(120)")
                        time.sleep(120)
                else:
                    must_send.send_code_email(content_text="网页无法打开,sleep(60)",title="打卡失败")
                    time.sleep(60)

            else:
                print("日期:["+daka_date+"]"+"Code:"+code+"\n")
                current_date = time.strftime(r"%Y%m%d")
                if daka_date < current_date :
                    must_send.send_code_email("当天第一次打卡邮件，初始化");
                
                time.sleep(60)
        else:
            print(receive)
            time.sleep(60)
    else:
        print(title)
        time.sleep(60)